<template>
  <div class="d_mainFlex">
    <div class="d_treeBox">
      <div class="maerMange">
        <div class="title">
          <h3>物料管理</h3>
        </div>
        <div class="treeList">
          <ul>
            <li
              :class="isAllMateriel?'on':''"
              @click="getllMateriels"
            >
              <i class="iconfont warIco" />
              <p>全部物料</p>
            </li>
          </ul>
        </div>
        <div class="title">
          <h3>基础数据</h3>
          <span class="c_3F61F1 pointer"  v-permission="'MenuCode5-10-1-6'" @click="addMaterirlClass=true"><i class="el-icon-plus" />新增分组</span>
        </div>
        <div class="d_nrBox">
          <div class="treeList">
            <ul>
              <li
                v-for="(item,index) in allMaterielClass"
                :key="item.groupID"
                :class="classIndex === index? 'on':''"
              >
                <div
                  class="flexLc flex_1"
                  @click="changeMaterClass(item,index)"
                >
                  <i class="iconfont folderIco" />
                  <p> {{ item.groupName }}({{ item.speciesQuantity }})</p>
                </div>
                <div class="kuOP">
                  <el-popover
                    :ref="`popover-${index}`"
                    placement="bottom"
                    popper-class="areasPopover"
                    trigger="click"
                  >
                    <div class="areasOp">
                      <ul>
                        <li v-permission="'MenuCode5-10-1-7'" @click="updateMaClass(item)">修改</li>
                        <li v-permission="'MenuCode5-10-1-8'" @click="deleteMaterielClass(item)">删除</li>
                      </ul>
                    </div>
                    <span slot="reference" class="el-icon-more c_3F61F1" />
                  </el-popover>
                </div>
              </li>
            </ul>
          </div>
          <div v-if="allMaterielClass.length==0" class="pl16 pr16">
            <el-skeleton :rows="10" animated />
          </div>
        </div>
        <!-- 物料所有分组       -->
      </div>
    </div>
    <div class="d_main">
      <div class="title">
        <h3>{{ subTitle }}({{ total || 0 }})</h3>
      </div>
      <!-- 操作区 S-->
      <div class="d_operationBox">
        <div class="d_btn">
          <el-button type="primary" size="small" icon="el-icon-plus" v-permission="'MenuCode5-10-1-1'" @click="newAddClick">新建</el-button>
        </div>
        <div class="d_search">
          <el-input
            v-model="search.likeWords"
            placeholder="请输入关键字"
            size="small"
            @keyup.enter.native="getAllMaterils"
          >
            <el-button
              slot="append"
              :loading="searchLoading"
              type="primary"
              icon="el-icon-search"
              :disabled="searchLoading"
              element-loading-spinner="el-icon-loading"
              @click="getAllMaterils"
            >
              搜索
            </el-button>
          </el-input>
        </div>
      </div>
      <!-- 操作区 E-->
      <!-- 表格操作区 S-->
      <div class="d_tableOperation">
        <div class="d_condition">
          <el-radio-group v-model="search.isDisable" size="mini" @change="getAllMaterils">
            <el-radio-button label="0">启用</el-radio-button>
            <el-radio-button label="1">禁用</el-radio-button>
          </el-radio-group>
        </div>
        <div class="d_set">
          <div @click="Refresh"><i class="d_icon el-icon-refresh-right" /></div>
          <div class="setting flex">
            <HeadSeting :list-data.sync="tableHead" :table-code="$config.goodslist" @reset="getTableHead" />
          </div>
        </div>
      </div>
      <!-- 表格操作区 E-->
      <!--table板块-->
      <div ref="tableCon" class="tableCon">
        <el-table
          v-show="tableHead.length>0"
          ref="multipleTable"
          v-loading="searchLoading"
          :data="allMaterirls"
          :height="tableHeight || 'auto'"
          border
          fit
          :row-key="getRowKeys"
          @header-dragend="surverWidth"
        >
          <el-table-column type="expand">
            <template slot-scope="{row}">
              <div class="dialogExpandTable">
                <el-table
                  :data="row.list || []"
                >
                  <el-table-column
                    prop="stockGoodsCode"
                    label="物料编号"
                    width="120"
                  />
                  <el-table-column
                    prop="stockGoodsName"
                    label="规格型号"
                    width="90"
                  />
                  <el-table-column
                    prop="supplierName"
                    label="供应商"
                    width="220"
                  />
                  <el-table-column
                    prop="averagePrice"
                    label="均价"
                    width="100"
                  />
                  <el-table-column
                    prop="purchaseMinPrice"
                    label="采购最低价"
                    width="100"
                  />
                  <el-table-column
                    prop="purchaseMaxPrice"
                    label="采购最高价"
                    width="100"
                  />
                  <el-table-column
                    prop="specificationJsValue"
                    label="转换比例"
                    width="100"
                  />
                  <el-table-column
                    prop="isOpenWarning"
                    label="预警启用"
                    width="90"
                  >
                    <template slot-scope="scope">
                      <div>
                        <template v-if="scope.row.isOpenWarning===0">
                          <span>禁用</span>
                        </template>
                        <template v-else-if="scope.row.isOpenWarning===1">
                          <span>开启</span>
                        </template>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="warningAmount"
                    label="库存预警"
                    show-overflow-tooltip
                    width="90"
                  />
                  <el-table-column
                    prop="areaShelfName"
                    label="默认库位"
                    show-overflow-tooltip
                    min-width="150"
                  />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <template v-for="(fruit,index) in tableHead">
            <el-table-column
              v-if="fruit.visible"
              :key="index"
              :label="fruit.columnName"
              :min-width="fruit.columnWidth || 90"
              :prop="fruit.columnCode"
              show-overflow-tooltip
              :fixed="fruit.isFloat?'left':false"
            >
              <template slot-scope="scope">
                <template v-if="fruit.columnCode==='isDisable'">
                  <template v-if="scope.row.isDisable===0">
                    <span>启用</span>
                  </template>
                  <template v-else-if="scope.row.isDisable===1">
                    <span>禁用</span>
                  </template>
                </template>
                <template v-else>
                  {{ scope.row[fruit.columnCode] }}
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="70px" align="center">
            <template slot-scope="scope">
              <div>
                <el-popover
                  :ref="`popover-${scope.$index}`"
                  placement="bottom-end"
                  popper-class="tableOp"
                  :popper-options="{ boundariesElement: 'opBox', removeOnDestroy: true }"
                  trigger="click"
                >
                  <div class="operation">
                    <ul >
                          <li
                            v-if="scope.row.isDisable===0"
                             v-permission="'MenuCode5-10-1-3'"
                            @click="optionsClick('enable',scope.row)"
                          >禁用
                          </li>
                          <li
                            v-if="scope.row.isDisable===1"
                             v-permission="'MenuCode5-10-1-2'"
                            @click="optionsClick('enable',scope.row)"
                          >启用
                          </li>
                        <li @click="optionsClick('see',scope.row)">查看</li>
                        <li v-permission="'MenuCode5-10-1-4'" @click="optionsClick('modify',scope.row)">修改</li>
                        <li v-permission="'MenuCode5-10-1-5'" @click="optionsClick('delete',scope.row)">删除</li>
                    </ul>
                  </div>
                  <div slot="reference" class="opBox pointer flexLcc"><span class="el-icon-more c_3F61F1" /></div>
                </el-popover>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 骨架屏     -->
        <div v-if="tableHead.length==0" class="p16">
          <el-skeleton :rows="6" animated />
        </div>
      </div>
      <!-- 分页 S-->
      <div class="d_pag">
        <pagination
          :total="total||0"
          :page.sync="search.pageIndex"
          :limit.sync="search.pageSize"
          @pagination="getAllMaterils"
        />
      </div>
      <!-- 分页 E-->
    </div>
    <!-- 新建物料   -->
    <el-dialog
      :title="ops==='add'? '新建物料' : '修改物料'"
      :visible.sync="isAddMaterriel"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <div class="subTip">
          <span><span class="mr5">物料编号：</span>{{ materForm.categoryCode || '系统自动生成' }}</span>
          <span class="mr15"><span class="mr5">创建日期：</span>{{
            materForm.billCreateTime || dayjs().format('YYYY-MM-DD')
          }}</span>
          <span><span class="mr5">创建人员：</span>{{ ops === 'add' ? name : materForm.createorName }}</span>
        </div>
        <div class="addWuliaoBox">
          <el-form
            ref="materForm"
            :model="materForm"
            :rules="materFormRules"
            label-width="80px"
            class="dialogForm dialogInlineForm"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="物料名称" prop="goodsName">
                  <el-input v-model="materForm.goodsName" placeholder="请输入内容" size="mini" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料类型" prop="categoryCode">
                  <el-select
                        filterable v-model="materForm.categoryCode" placeholder="物料类型" size="mini">
                    <el-option
                      v-for="item in allMaterielTypes"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料分组" prop="groupCode">
                  <el-select
                        filterable v-model="materForm.groupCode" placeholder="物料分组" size="mini">
                    <el-option
                      v-for="item in allMaterielClass"
                      :key="item.groupID"
                      :label="item.groupName"
                      :value="item.groupCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="物料单位" prop="goodsUnitCode">
                  <el-select
                        filterable v-model="materForm.goodsUnitCode" placeholder="物料单位" size="mini">
                    <el-option
                      v-for="item in materielCompany"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计价单位">
                  <div class="flex">
                    <div class="mr10">
                      <el-switch
                        v-model="materForm.isPriceUnit"
                        active-color="#3F61F1"
                        inactive-color="#D2D5DA"
                        @change="handleSwitchChange"
                      />
                    </div>
                    <div class="flex1">
                      <el-select
                        filterable v-model="materForm.priceUnitCode" placeholder="计价单位" size="mini" :disabled="!materForm.isPriceUnit">
                        <el-option
                          v-for="item in materielCompany"
                          :key="item.code"
                          :label="item.name"
                          :value="item.code"
                        />
                      </el-select>
                    </div>
                  </div>

                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="物料备注" class="inlineText mt5">
              <el-input v-model="materForm.goodsDesc" type="textarea" placeholder="物料备注" size="mini" clearable />
            </el-form-item>
          </el-form>
          <div class="tableBox lastTdNoBorder">
            <div class="tt flex flex_between">
              <span class="fw">规格型号</span>
              <span class="c_3F61F1 mr15 pointer" @click="addSpecs"><i class="el-icon-plus mr5" /> 新增</span>
            </div>
            <el-table
              :data="materForm.list"
              border
              style="width: 100%"
            >
              <el-table-column
                label="规格型号"
                min-width="110"
                prop="stockGoodsName"
              />
              <el-table-column
                label="供应商"
                min-width="120"
                show-overflow-tooltip
                prop="supplierName"
              />
              <el-table-column
                label="转换比例"
                min-width="110"
                prop="specificationJsValue"
              />
              <el-table-column
                label="均价"
                min-width="110"
                prop="averagePrice"
              />
              <el-table-column
                label="采购最低价"
                min-width="110"
                prop="purchaseMinPrice"
              />
              <el-table-column
                label="采购最高价"
                show-overflow-tooltip
                min-width="110"
                prop="purchaseMaxPrice"
              />
              <el-table-column
                label="快捷键"
                show-overflow-tooltip
                min-width="150"
                prop="searchHotKeys"
              />
              <el-table-column
                label="备注"
                show-overflow-tooltip
                min-width="150"
                prop="stockGoodsDesc"
              />
              <el-table-column
                label="操作"
                fixed="right"
                show-overflow-tooltip
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                <div style="display:flex;justify-content: center">
                  <el-tooltip class="item" effect="dark" content="复制" placement="left-start">
                    <span class="mr15 pointer" @click="specsCopy(scope.row)"><i class="el-icon-copy-document" /></span>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="编辑" placement="left-start">
                    <span class="mr15 pointer" @click="specsEdit(scope.row,scope.$index)"><i class="el-icon-edit-outline" /></span>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除" placement="right-start">
                    <span class="pointer" @click="specsDelete(scope.$index,scope.row)"><i
                      class="el-icon-delete"
                    /></span>
                  </el-tooltip>
                </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddMaterriel=false">取 消</el-button>
        <!--  新建保存      -->
        <el-button
          v-if="ops==='add'"
          v-loading="addMaterrielLoading"
          :disabled="addMaterrielLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveMater"
        >保存</el-button>
        <!--  修改保存      -->
        <el-button
          v-if="ops==='modify'"
          v-loading="addMaterrielLoading"
          :disabled="addMaterrielLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveEditMater"
        >保存</el-button>
      </div>
    </el-dialog>
    <!-- 查看物料   -->
    <el-dialog
      title="查看物料"
      :visible.sync="isSeeMaterriel"
      :close-on-click-modal="false"
      custom-class="bodyNoPadDialog bigDialog"
      width="85%"
      @close="closeDialog"
    >
      <div class="dialogDody">
        <div class="subTip">
          <span class="mr15"><span class="mr5">物料编号：</span>{{ materForm.categoryCode || '系统自动生成' }}</span>
          <span class="mr15"><span class="mr5">创建日期：</span>{{ materForm.createTime || dayjs().format('YYYY-MM-DD') }}</span>
          <span><span class="mr5">创建人员：</span>{{ ops === 'add' ? name : materForm.createorName }}</span>
        </div>
        <div class="addWuliaoBox">
          <el-form
            ref="materForm"
            disabled
            :model="materForm"
            label-width="80px"
            class="dialogForm dialogInlineForm"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="物料名称" prop="goodsName">
                  <el-input v-model="materForm.goodsName" placeholder="请输入内容" size="mini" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料类型" prop="categoryCode">
                  <el-select
                        filterable v-model="materForm.categoryCode" placeholder="物料类型" size="mini">
                    <el-option
                      v-for="item in allMaterielTypes"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="物料分组" prop="groupCode">
                  <el-select
                        filterable v-model="materForm.groupCode" placeholder="物料分组" size="mini">
                    <el-option
                      v-for="item in allMaterielClass"
                      :key="item.groupID"
                      :label="item.groupName"
                      :value="item.groupCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="物料单位" prop="goodsUnitCode">
                  <el-select
                        filterable v-model="materForm.goodsUnitCode" placeholder="物料单位" size="mini">
                    <el-option
                      v-for="item in materielCompany"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="计价单位">
                  <div class="flex">
                    <div class="mr10">
                      <el-switch
                        v-model="materForm.isPriceUnit"
                        active-color="#3F61F1"
                        inactive-color="#D2D5DA"
                      />
                    </div>
                    <div class="flex1">
                      <el-select
                        filterable v-model="materForm.priceUnitCode" placeholder="计价单位" size="mini" :disabled="!materForm.isPriceUnit">
                        <el-option
                          v-for="item in materielCompany"
                          :key="item.code"
                          :label="item.name"
                          :value="item.code"
                        />
                      </el-select>
                    </div>
                  </div>

                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="物料备注" class="inlineText mt5">
              <el-input v-model="materForm.goodsDesc" type="textarea" placeholder="物料备注" size="mini" clearable />
            </el-form-item>
          </el-form>
          <div class="tableBox lastTdNoBorder">
            <div class="tt flex flex_between">
              <span class="fw">物料规格型号</span>
            </div>
            <el-table
              :data="materForm.list"
              border
              style="width: 100%"
            >
              <el-table-column
                label="规格型号"
                min-width="110"
                prop="stockGoodsName"
              />
              <el-table-column
                label="供应商"
                min-width="120"
                show-overflow-tooltip
                prop="supplierName"
              />
              <el-table-column
                label="转换比例"
                min-width="110"
                prop="specificationJsValue"
              />
              <el-table-column
                label="默认库位"
                min-width="110"
                prop="areaShelfName"
              />
              <el-table-column
                label="均价"
                min-width="110"
                prop="averagePrice"
              />
              <el-table-column
                label="采购最低价"
                min-width="110"
                prop="purchaseMinPrice"
              />
              <el-table-column
                label="采购最高价"
                show-overflow-tooltip
                min-width="110"
                prop="purchaseMaxPrice"
              />
              <el-table-column
                label="快捷键"
                show-overflow-tooltip
                min-width="150"
                prop="searchHotKeys"
              />
              <el-table-column
                label="备注"
                show-overflow-tooltip
                min-width="150"
                prop="stockGoodsDesc"
              />
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isSeeMaterriel=false">取 消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="isSeeMaterriel=false"
        >确定</el-button>
      </span>
    </el-dialog>
    <!-- 新建规格型号   -->
    <el-dialog
      :title="title+'规格型号'"
      :visible.sync="specsVisible"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="35%"
      @close="closeSpecsDialog"
    >
      <div class="dialogDody">
        <el-form
          ref="specsForm"
          :model="specsForm"
          :rules="specsRules"
          label-width="80px"
          class="dialogForm"
        >
          <el-form-item label="物料名称">
            <el-input v-model="materForm.goodsName" placeholder="物料名称" size="mini" disabled />
          </el-form-item>
          <el-form-item label="供应商" prop="supplierObj">
            <el-select
                        filterable v-model="specsForm.supplierObj" placeholder="供应商" size="mini" clearable value-key="supplierCode" filterable @change="supplierChange">
              <el-option
                v-for="item in allSupliers"
                :key="item.supplierCode"
                :label="item.supplierName"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规格型号" prop="stockGoodsName">
            <el-input v-model="specsForm.stockGoodsName" placeholder="规格型号" size="mini" clearable />
          </el-form-item>
          <el-form-item label="转换比例" prop="specificationJsValue">
            <el-input v-model="specsForm.specificationJsValue" type="number" placeholder="转换比例" size="mini" :disabled="!materForm.isPriceUnit" clearable @change="toOne">
              <template slot="append">{{ getPriceUnitName || '--' }}</template>
            </el-input>
          </el-form-item>
          <el-form-item label="默认库位">
            <el-cascader
              v-model="specsForm.warehouseAreas"
              size="mini"
              :options="storageLocations"
              :props="{ value: 'code',label: 'name' }"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="预警启用">
            <div class="flex">
              <div class="mr10">
                <el-switch
                  v-model="specsForm.isOpenWarning"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#3F61F1"
                  inactive-color="#D2D5DA"
                />
              </div>
              <div class="flex1">
                <el-input v-model="specsForm.warningAmount" placeholder="预警数量" size="mini" clearable :disabled="!specsForm.isOpenWarning" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="快捷键">
            <el-input v-model="specsForm.searchHotKeys" placeholder="规格型号" size="mini" clearable />
          </el-form-item>
          <el-form-item label="备注" class="mt5">
            <el-input v-model="specsForm.stockGoodsDesc" type="textarea" :rows="2" placeholder="规格型号" size="mini" clearable />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="specsVisible=false">取 消</el-button>
        <el-button
          v-if="specsOps === 'add'"
          v-loading="addMaterClassLoading"
          :disabled="addMaterClassLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="continueSaveSpecsForm"
        >继续新增</el-button>
        <el-button
          v-loading="addMaterClassLoading"
          :disabled="addMaterClassLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveSpecsForm"
        >保存</el-button>
      </div>
    </el-dialog>
    <!-- 新建物料分组   -->
    <el-dialog
      title="新建物料分组"
      :visible.sync="addMaterirlClass"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="35%"
      @close="closeClassDialog"
    >
      <div class="dialogDody">
        <el-form
          ref="materClassForm"
          :model="materClassForm"
          :rules="materClassRules"
          label-width="80px"
          class="dialogForm"
        >
          <el-form-item label="分组名称" prop="groupName">
            <el-input v-model="materClassForm.groupName" placeholder="分组名称" size="mini" clearable />
          </el-form-item>
          <el-form-item label="排序" prop="groupName">
            <el-input v-model="materClassForm.groupSort" placeholder="分组名称" size="mini" clearable />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addMaterirlClass=false">取 消</el-button>
        <el-button
          v-loading="addMaterClassLoading"
          :disabled="addMaterClassLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveMaterClass"
        >保存</el-button>
      </div>
    </el-dialog>
    <!-- 编辑物料分组   -->
    <el-dialog
      title="编辑物料分组"
      :visible.sync="editMaterirlClass"
      :close-on-click-modal="false"
      custom-class="comDialog"
      width="35%"
      @close="closeClassDialog"
    >
      <div class="dialogDody">
        <el-form
          ref="editMaterClassForm"
          :model="materClassForm"
          :rules="materClassRules"
          label-width="80px"
          class="dialogForm"
        >
          <el-form-item label="分组名称" prop="groupName">
            <el-input v-model="materClassForm.groupName" placeholder="分组名称" size="mini" clearable />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editMaterirlClass=false">取 消</el-button>
        <el-button
          v-loading="addMaterClassLoading"
          :disabled="addMaterClassLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveEditMaterClass"
        >保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { arraySort, limitInputNumber } from '@/utils'
import HeadSeting from '@/components/HeadSeting'
import Pagination from '@/components/Pagination'
import pinyin from 'js-pinyin'
import { mapGetters } from 'vuex'

export default {
  name: 'Materiel',
  components: { Pagination, HeadSeting },
  computed: {
    ...mapGetters([
      'name'
    ]),
    getPriceUnitName() {
      const code = this.materForm.priceUnitCode
      const arr = this.materielCompany ? this.materielCompany : []
      const obj = arr.length > 0 ? arr.find(m => m.code === code) : {}
      return obj && obj.name || ''
    }
  },
  data() {
    return {
      ops: 'add', // 物料操作、新建，修改，查看
      specsOps: 'add', // 规格型号操作
      specsIndex: null, // 规格型号编辑行的索引
      specsVisible: false, // 新建规格型号是否打开
      subTitle: '全部物料',
      tableHeight: null, // 表格最大高度
      addMaterirlClass: false, // 新建物料分组弹框是否打开
      editMaterirlClass: false, // 编辑物料分组弹框是否打开
      addMaterClassLoading: false, // 新建物料分组加载效果
      isSeeMaterriel: false, // 查看物料弹框是否打开
      isAddMaterriel: false, // 新建物料弹框是否打开
      title:'新建',
      addMaterrielLoading: false, // 新建物料保存加载
      isAllMateriel: true, // 全部物料
      classIndex: null, // 选中分组索引
      searchLoading: false, // 搜索加载效果
      allMaterirls: [], // 全部物料数据列表
      allMaterielClass: [], // 所有物料分组
      allMaterielTypes: [], // 物料类型
      materielCompany: [], // 物料单位
      allSupliers: [], // 所有供应商列表
      expands: [], // 要展开的行，数值的元素是row的key值
      isEnabled: null,
      operations: [
        [{ text: '查看', key: 'see' }, { text: '修改', key: 'modify' }],
        [{ text: '启用', key: 'enable' }],
        [{ text: '删除', key: 'delete' }]
      ], // 表格操作
      // 物料分组表单
      materClassForm: {
        groupName: '',
        groupSort: 1000
      },
      backupsGroupCode: '',
      // 新建物料表单
      materForm: {
        goodsID: '',
        groupCode: '',
        categoryCode: '',
        isPriceUnit: false,
        priceUnitCode: '',
        goodsName: '',
        goodsUnitCode: '',
        searchHotKeys: '',
        goodsDesc: '',
        list: []
      },
      specsForm: {
        stockGoodsID: '',
        goodsCode: '系统自动生成',
        stockGoodsName: '', // 规格型号
        specification: '',
        supplierName: '',
        supplierCode: '',
        supplierObj: {}, // 供应商对象
        goodsUnitCode: '', // 单位code
        specificationJsValue: 1, // 转换比例
        areaShelfCode: '', // 库位code
        areaShelfName: '', // 库位名称
        warehouseAreaCode: '', // 库区code
        warehouseAreaName: '', // 库区名称
        warehouseAreas: [], // 库区库位数组
        averagePrice: '--', // 均价
        purchaseMinPrice: '--', // 采购最低价
        purchaseMaxPrice: '--', // 采购最高价
        isOpenWarning: false,
        warningAmount: 100, // 预警数量
        searchHotKeys: '',
        stockGoodsDesc: ''
      }, // 规格型号表单
      storageLocations: [], // 库区库位
      // 物料搜索条件
      search: {
        pageIndex: 1,
        pageSize: 30,
        likeWords: '',
        groupCode: '',
        categoryCode: '',
        goodsCode: '',
        goodsUnitCode: '',
        isDisable: 0
      },
      total: 0, // 物料总条数
      rowID:'',
      tableHead: [], // 物料表格表头
      materClassRules: {
        groupName: [
          { required: true, message: '请输入分组名称', trigger: 'blur' }
        ]
      },
      materFormRules: {
        goodsName: [
          { required: true, message: '请输入物料名称', trigger: 'blur' }
        ],
        groupCode: [
          { required: true, message: '请选择物料分组', trigger: 'change' }
        ],
        categoryCode: [
          { required: true, message: '请选择物料类型', trigger: 'change' }
        ],
        goodsUnitCode: [
          { required: true, message: '请选中物料单位', trigger: 'change' }
        ]
      },
      specsRules: {
        supplierObj: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        stockGoodsName: [
          { required: true, message: '请填写规格型号', trigger: 'blur' }
        ],
        specificationJsValue: [
          { required: true, message: '请填写转换比例', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 所有物料列表数据
    this.getAllMaterils()
    // 物料表格得表头
    this.getTableHead()
    // 获取所有物料分组
    this.getMaterielClass()
    // 物料类型
    this.getMarTypes()
    // 物料单位
    this.getMarCompany()
    // 供应商
    this.getSupplier()
    // 库区库位
    this.getStorageLocations()
  },
  mounted() {
    // 表格高度
    this.calHeight()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.multipleTable.doLayout()
    })
  },
  methods: {
    getRowKeys(row) {
      return row.goodsID
    },
    expandChange(row,expanded) {
      this.expands = []
      if(expanded.length>0){
        this.expands.push(row.goodsID)
      }
    },
    // 主列表规格型号删除
    deleteSpecs(id) {
      const parmas = {
        entityID: id
      }
      this.$confirm('确定删除该采购?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.mater.DeleteStockGoods(parmas).then(res => {
          if (res.isDelete) {
            this.getAllMaterils()
            this.$message({
              message: '删除规格信号成功',
              type: 'warning'
            })
          } else {
            this.$message({
              message: '该规格型号已使用,不能删除',
              type: 'warning'
            })
          }
        })
      })
    },
    toOne(e) {
      if (e <= 0) {
        this.$message({
          message: '转换比例必须大于0',
          type: 'warning'
        })
        this.specsForm.specificationJsValue = 1
      }
      // this.specsForm.specificationJsValue = limitInputNumber(
      //   e,
      //   Infinity,
      //   0,
      //   6
      // )
    },
    // 规格型号编辑点击事件
    specsEdit(item, index) {
      this.title = '编辑'
      this.specsForm = Object.assign({}, item)
      this.specsForm.supplierObj = {}
      this.specsForm.warehouseAreas = []
      if(item.warehouseAreaCode){
        this.specsForm.warehouseAreas[0] = item.warehouseAreaCode
        this.specsForm.warehouseAreas[1] = item.areaShelfCode
      }
      this.specsForm.supplierObj.supplierCode = item.supplierCode
      this.specsForm.supplierObj.supplierName = item.supplierName
      this.specsOps = 'modify'
      this.specsIndex = index
      this.specsVisible = true
    },
    // 库区库位改变事件
    handleChange(arr) {
      if (!arr) return
      this.specsForm.warehouseAreaCode = arr[0]
      this.specsForm.areaShelfCode = arr[1]
    },
    // 规格型号继续新增
    continueSaveSpecsForm() {
      this.$refs.specsForm.validate((valid) => {
        if (valid) {
          // this.closeSpecsDialog()
          this.specsForm.supplierObj.supplierCode = this.allSupliers[0].supplierCode
          this.specsForm.supplierObj.supplierName = this.allSupliers[0].supplierName
          const spsForm = JSON.parse(JSON.stringify(this.specsForm))
          this.materForm.list.push(spsForm)
          this.specsForm.stockGoodsName = ''
          this.goodsNameChange()
        }
      })
    },
    // 新增规格型号保存事件
    saveSpecsForm() {
      this.$refs.specsForm.validate((valid) => {
        if (valid) {
          if (this.specsOps === 'add') {
            const spsForm = JSON.parse(JSON.stringify(this.specsForm))
            this.materForm.list.push(spsForm)
            this.specsVisible = false
          } else {
            const spsForm = JSON.parse(JSON.stringify(this.specsForm))
            this.$set(this.materForm.list, this.specsIndex, spsForm)
            this.specsVisible = false
          }
        }
      })
    },
    // 库区库位
    getStorageLocations() {
      const parmas = {
        warehouseCode: '',
        likeWords: ''
      }
      this.$api.warehouse.GetStockQueryAreaTreeView(parmas).then(res => {
        this.storageLocations = res
      })
    },
    // 供应商选择改变事件
    supplierChange(item) {
      this.specsForm.supplierCode = item.supplierCode
      this.specsForm.supplierName = item.supplierName
    },
    // 物料名称输入改变事件
    goodsNameChange() {
      const name = this.materForm.goodsName
      setTimeout(() => {
        pinyin.setOptions({ checkPolyphone: false, charCase: 0 })
        this.specsForm.searchHotKeys = pinyin.getCamelChars(name)
      }, 300)
    },
    // 新建物料点击事件
    newAddClick() {
      this.ops = 'add'
      this.materForm.groupCode = this.backupsGroupCode
      this.isAddMaterriel = true
    },
    // 新建物料保存
    saveMater() {
      const parmas = this.materForm
      this.$refs.materForm.validate((valid) => {
        if (valid) {
          this.addMaterrielLoading = true
          this.$api.mater.getAddGoods(parmas).then(() => {
            this.isAddMaterriel = false
            this.addMaterrielLoading = false
            this.getAllMaterils()
            // 获取所有物料分组
            this.getMaterielClass()
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          }).catch(() => {
            this.addMaterrielLoading = false
          })
        }
      })
    },
    // 保存编辑物料
    saveEditMater() {
      const parmas = this.materForm
      this.$refs.materForm.validate((valid) => {
        if (valid) {
          this.addMaterrielLoading = true
          this.$api.mater.UpdateGoods(parmas).then(() => {
            this.isAddMaterriel = false
            this.addMaterrielLoading = false
            this.getAllMaterils()
            // 获取所有物料分组
            this.getMaterielClass()
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          }).catch(() => {
            this.addMaterrielLoading = false
          })
        }
      })
    },
    // 规格删除
    specsDelete(index, data) {
      if (data.stockGoodsID) {
        const parmas = {
          entityID: data.stockGoodsID
        }
        this.$api.mater.DeleteStockGoods(parmas).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            // this.getMaterielInfo(this.rowID)
            this.materForm.list.splice(index, 1)
        })
      } else {
        this.materForm.list.splice(index, 1)
      }
    },

    //计价单位开关切换事件
    handleSwitchChange(e){
      if(!e){
        this.materForm.priceUnitCode = ''
      }
    },
    // 规格复制
    specsCopy(item) {
      const arr = { ...item }
      arr.stockGoodsID = ''
      arr.goodsCode = ' '
      this.materForm.list.push(arr)
    },
    // 供应商
    getSupplier() {
      this.$api.mater.GetAllSuppliers().then(res => {
        this.allSupliers = res
        this.specsForm.supplierCode = res[0].supplierCode
        this.specsForm.supplierName = res[0].supplierName

      })
    },
    // 物料单位
    getMarCompany() {
      const parmas = {
        DictionaryCode: 'GoodsUnit'
      }
      this.$api.mater.GetAllGoodsUnits(parmas).then(res => {
        this.materielCompany = res
        this.materForm.priceUnitCode = res[0].code
      })
    },
    // 物料类型
    getMarTypes() {
      const parmas = {
        DictionaryCode: 'GoodsCategory'
      }
      this.$api.mater.GetAllGoodsUnits(parmas).then(res => {
        this.allMaterielTypes = res
      })
    },
    // 物料详情
    getMaterielInfo(id) {
      const parmas = {
        queryBy: 1,
        queryValue: id
      }
      this.$api.mater.GetSingleGoods(parmas).then(res => {
        const data = JSON.parse(JSON.stringify(res))
        data.isPriceUnit = !!data.priceUnitCode
        this.materForm = data
        this.materForm.list = res.list
      })
    },
    // 新增规格点击事件
    addSpecs() {
      this.specsOps = 'add'
      this.title = '新建'
            this.specsVisible = true
            this.specsForm.supplierObj.supplierCode = this.allSupliers[0].supplierCode
        this.specsForm.supplierObj.supplierName = this.allSupliers[0].supplierName
      // this.$refs.materForm.validate((valid) => {
      //   if (valid) {
      //     // 物料名称输入改变事件
      //     this.goodsNameChange()
      //   }
      // })
    },
    // 表格操作方法
    optionsClick(key, data) {
      this.rowID = data.goodsID
      if (key === 'enable') {
        // 启用/禁用设置
        this.setMateriel(data.goodsID)
      } else if (key === 'delete') {
        // 删除
        this.deleteMar(data.goodsID)
      } else if (key === 'modify') {
        this.ops = 'modify'
        // 物料详情
        this.getMaterielInfo(data.goodsID)
        this.isAddMaterriel = true
      } else if (key === 'see') {
        this.ops = 'see'
        // 物料详情
        this.getMaterielInfo(data.goodsID)
        this.isSeeMaterriel = true
      }
    },
    // 设置物料状态
    setMateriel(id) {
      const parmas = {
        entityID: id
      }
      this.$confirm('确定启用/禁用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.mater.SetGoodsState(parmas).then(() => {
          this.getAllMaterils()
          // 获取所有物料分组
          this.getMaterielClass()
          this.$message({
            message: '设置成功',
            type: 'success'
          })
        })
      })
    },
    // 删除物料
    deleteMar(id) {
      const parmas = {
        entityID: id
      }
      this.$confirm('确定删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.mater.DeleteGoods(parmas).then(() => {
          this.getAllMaterils()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      })
    },
    // 保存表头样式变化
    saveHead(newArray) {
      const parmas = newArray
      setTimeout(() => {
        this.$api.common.saveTableStyle(parmas).then(() => {
        })
      }, 300)
    },
    // 保存表头列宽度
    surverWidth(newWidth, oldWidth, column) {
      setTimeout(() => {
        const heads = [...this.tableHead]
        heads.forEach(item => {
          if (item.columnCode === column.property) {
            item.columnWidth = column.width
            return
          }
        })
        this.saveHead(heads)
      }, 100)
    },
    // 表格最大高度
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.tableCon.getBoundingClientRect()
        this.tableHeight = rect.height
      })
    },
    // 删除物料分组
    deleteMaterielClass(data) {
      const parmas = {
        entityID: data.groupID
      }
      this.$confirm('确定删除该分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.mater.DeleteGoodsGroup(parmas).then(() => {
          this.getMaterielClass()
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      })
    },
    // 物料分组详情
    updateMaClass(data) {
      this.editMaterirlClass = true
      this.materClassForm.groupName = data.groupName
      this.materClassForm.groupID = data.groupID
    },
    // 编辑物料分组
    saveEditMaterClass() {
      const parmas = this.materClassForm
      this.$refs.editMaterClassForm.validate((valid) => {
        if (valid) {
          this.addMaterClassLoading = true
          this.$api.mater.UpdateGoodsGroup(parmas).then(() => {
            this.getMaterielClass()
            this.addMaterClassLoading = false
            this.editMaterirlClass = false
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          }).catch(() => {
            this.addMaterClassLoading = false
          })
        }
      })
    },
    // 新建物料分组
    saveMaterClass() {
      const parmas = this.materClassForm
      this.$refs.materClassForm.validate((valid) => {
        if (valid) {
          this.addMaterClassLoading = true
          this.$api.mater.AddGoodsGroup(parmas).then(() => {
            this.getMaterielClass()
            this.addMaterirlClass = false
            this.addMaterClassLoading = false
            this.$message({
              message: '新建成功',
              type: 'success'
            })
          }).catch(() => {
            this.addMaterClassLoading = false
          })
        }
      })
    },
    // 物料分组改变事件
    changeMaterClass(item, index) {
      this.isAllMateriel = false
      this.classIndex = index
      this.search.groupCode = item.groupCode
      this.backupsGroupCode = item.groupCode
      this.subTitle = item.groupName
      this.getAllMaterils()
    },
    // 全部物料
    getllMateriels() {
      this.isAllMateriel = true
      this.materClassForm = this.$options.data().materClassForm
      this.search.groupCode = ''
      this.backupsGroupCode = ''
      this.classIndex = null
      this.subTitle = '全部物料'
      this.getAllMaterils()
    },
    // 全部物料，清除所有查询条件
    Refresh() {
      this.search = this.$options.data().search
      this.getAllMaterils()
    },
    // 获取所有物料分组
    getMaterielClass() {
      this.$api.mater.GetAllGoodsGroupData().then(res => {
        this.allMaterielClass = res
      })
    },
    // 获取物料表格表头
    getTableHead() {
      const parmas = {
        tableCode: this.$config.goodslist
      }
      this.$api.common.getAllTableHead(parmas).then(res => {
        res.sort(arraySort('columnSort'))
        this.tableHead = res
      })
    },
    // 所有物料列表数据
    getAllMaterils() {
      const parmas = this.search
      this.searchLoading = true
      this.$api.mater.GetMatchPageGoods(parmas).then(res => {
        this.allMaterirls = res.list
        this.allMaterirls.forEach((item)=>{
            for(let i in item){
              if(!item[i] && item[i] !== 0){
                item[i] = '--'
              }
            }
          })
        this.total = res.totalCount
        this.searchLoading = false
      }).catch(() => {
        this.searchLoading = false
      })
    },
    // 物料分组弹框关闭事件
    closeClassDialog() {
      // 关闭弹框的时候清空数据
      if (this.$refs.materClassForm) {
        this.$refs.materClassForm.resetFields()
      }
      if (this.$refs.editMaterClassForm) {
        this.$refs.editMaterClassForm.resetFields()
      }
      this.materClassForm = this.$options.data().materClassForm
    },
    // 物料新建弹框关闭事件
    closeDialog() {
      if (this.$refs.materForm) {
        this.$refs.materForm.resetFields()
      }
      this.materForm = this.$options.data().materForm
    },
    // 新建规格型号弹框关闭事件
    closeSpecsDialog() {
      if (this.$refs.specsForm) {
        this.$refs.specsForm.resetFields()
      }
      this.specsForm = this.$options.data().specsForm
    }
  }
}
</script>
<style lang="scss" scoped>
.spot{
  width: 6px;
  height: 6px;
  display: inline-block;
  border-radius: 100%;
}
.addWuliaoBox {
  padding: 10px 16px;

  .tableBox {
    margin-top: 16px;
    border: 1px solid #e6e6e6;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    overflow: hidden;

    .tt {
      height: 38px;
      line-height: 38px;
      padding-left: 16px;
      background: #f7f8fa;
      border-radius: 8px 8px 0 0;
    }
  }
}

.subTip {
  border-bottom: 1px #e6e6e6 solid;
  background: #f5f6f9;
  padding: 8px 16px;
}

.container {
  height: 100%;
}

.permangeRg {
  border: 1px solid #e6e6e6;
  background: #fff;
  margin-left: 18px;
  height: 100%;

  .mainTT {
    font-size: 16px;
    font-weight: bold;
    width: 100%;
    padding: 18px 16px;
    padding-bottom: 0;
  }
}

.permanageLf {
  width: 280px;
  height: 100%;
  border: 1px solid #e6e6e6;
  background: #fff;

  .kuOP {
    display: none;
  }

  li {
    padding: 9px 16px;
    cursor: pointer;

    &:hover {
      background: #3f61f110;
      color: #3f61f1;

      .kuOP {
        display: block !important;
      }
    }
  }

  li.on {
    background: #3f61f110;
    color: #3f61f1;
  }

  .allMateriel {
    line-height: 44px;
    padding-left: 16px;

    &:hover {
      background: #3f61f110;
      color: #3f61f1;
    }
  }

  .allMateriel.crt {
    background: #3f61f110;
    color: #3f61f1;
  }
}

.navTT {
  line-height: 22px;
  padding: 16px;
}

.areasOp {
  li {
    padding: 8px 16px;
    cursor: pointer;

    &:hover {
      background: #F6F6F6;
    }
  }
}
</style>
